<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Controller;
use think\Db;
use Qiniu\Auth;
use OSS\OssClient;
use OSS\Core\OssException;
class  Base extends Controller {
    protected $_error;
    protected $_header;//用户的请求头信息
    protected $otherLogin  = '您的账号已在其他设备登录';
    protected $frost = '您的账号已被冻结';
    protected $del = '您的账号已被删除';
    // 构造函数
    public function _initialize(){
        // 如果配置项为空 则直接返回

    }

    /**
     * 验证唯一——单点登录
     * user_id，time，salt，value
     * @return string
     */
    public  function checkAll($uid,$time,$value,$reqKey){
        if($uid == 0) {
            return 111;
        } else {
            $user = Db::table('up_u_user')->where('user_id',$uid)->find();
            if($user['user_status'] == 2){ // 冻结
                return 110;
            }
            if($user['user_status'] == 3){ // 删除
                return 1103;
            }
            $token = $user['user_token'];
            $appId = "D20201011101215";
            $appkey = "9DA807B0-BE10-U511-6998-6I57B0CCE8ON";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey) {
                return 112;
            } else {
                return 111;
            }
        }
    }
    /**
     * 获取七牛token
     * @return string
     */
    public function getQiniuToken(){
        require_once ('../extend/qiniu/autoload.php');
        header("Access-Control-Allow-Origin:*");
        $accessKey = config('qiniu')['accessKey'];
        $secretKey = config('qiniu')['secretKey'];
        $bucket = config('qiniu')['bucket'];
//        $auth = new Qiniu();
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        return json_encode(array('data'=>$token));
    }
    /**
     * 云之讯发送短信
     * @param $phone
     * @param $num
     * @return mixed
     */
    public function duaxin($phone,$num){
        $SpCode = '230149';
        $LoginName = 'js_px';
        $Password = 'panson58398860';
        $MessageContent = iconv("UTF-8", "gbk//TRANSLIT", "您的验证码为{$num}，请在10分钟内使用！");
        $body = "SpCode=$SpCode&LoginName=$LoginName&Password=$Password&MessageContent=$MessageContent&UserNumber=$phone&SerialNumber=&ScheduleTime=&f=1";
        $header = array(
            'Accept:application/x-www-form-urlencoded',
            'Content-Type: application/x-www-form-urlencoded; charset=gbk'
        );
        $url = 'https://api.ums86.com:9600/sms/Api/Send.do';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $result = mb_convert_encoding($result,'UTF-8','GBk');
        $res = explode('&',$result);
        return $res;
    }
    /**
     * param $tmp
     * param $name
     * param $size
     * 上传图片
     */
//    public function uploadFile($tmp,$name,$size)
    public function uploadFile()
    {
        $tmp = $_FILES['image']['tmp_name'];
        $name = $_FILES['image']['name'];
        $size = $_FILES['image']['size'];
        if($size > 1024*1024*5){
            return json_encode(['status'=>0,'msg'=>"图片不得超过5M！"]);
        }
        $imgarray = array('jpg','jpeg','png');
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        if($tmp){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$name);
            $exe = end($exe);
//            if(!in_array($exe,$imgarray)){
//                return json_encode(['status'=>0,'msg'=>'图片格式不支持']);
//            }
//            $newName = $rand . '.' .$exe;
            $newName = $rand . '.png';
            //=======================
            if(move_uploaded_file($tmp,"{$dir}/image/{$newName}")){
                $imgUrl = "{$url}/image/{$newName}";
                if($size > 1024*1024*2){
                    $this->image_png_size_add("{$dir}/image/{$newName}","{$dir}/image/{$newName}");
                }
                return json_encode(['status'=>200,'msg'=>$imgUrl]);
            }else{
                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>"上传一张图！"]);
        }
    }

    /**
     * 压缩图片
     * @param $imgsrc:原图片地址（完整的图片路径）
     * @param $imgdst:压缩后的图片地址，也是完整的
     */
    function image_png_size_add($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        switch($type){
            case 1:
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image = imagecreatefromjpeg($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
            case 3:
                header('Content-Type:image/png');
                $image = imagecreatefrompng($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
        }
    }

    /**
     * formatTime 时间格式化
     * @param $time 时间戳
     * @return string
     */
    public function formatTime($time) {
        $now_time = time();
        $t = $now_time - $time;
        $yea = (int) ($t / (86400 * 30 * 12));
        if ($yea >= 1) {
            return $yea.'年前';
        }
        $mon = (int) ($t / (86400 * 30));
        if ($mon >= 1) {
            return '一个月前';
        }
        $day = (int) ($t / 86400);
        if ($day >= 1) {
            return $day . '天前';
        }
        $h = (int) ($t / 3600);
        if ($h >= 1) {
            return $h . '小时前';
        }
        $min = (int)($t / 60);
        if ($min >= 1) {
            return $min . '分钟前';
        }
        return '刚刚';
    }

    /**
     * 获取任意长度的随机字符串
     * @param $length
     * @return string
     */
//    function getRandChar($length)
//    {
//        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
//            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
//            't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
//            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
//            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
//            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
//        $char_txt = '';
//        for ($i = 0; $i < $length; $i++) {
//            $char_txt .= $chars[array_rand($chars)];
//        }
//        return $char_txt;
//    }

    /**
     * 验证码
     * @param $length
     * @return string
     */
    function getCodeChar($length)
    {
        $chars = array(
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }
    public function getAcount()
    {
        //==========base里放到===============
        $zimu = range('a','z');
        $one = rand(0,25);
        $two = rand(0,25);
        $thr = rand(0,25);
        $four = rand(0,25);
        $zimu2 = $zimu[$one].$zimu[$two].$zimu[$thr].$zimu[$four];
        $num = rand(100000,999999);
        return $zimu2.$num;
        //=========================
    }

    //------------------------mww-------------------------------------------------------

    /**
     * 支付回调处理
     */
    public function alltypespay($num,$back_order_id)
    {
        $today = date('Y-m-d H:i:s');
        $order = Db::table('up_order')
            ->where('order_number',$num)
            ->field('order_id,order_status,order_coin,order_user_pay,order_user_id')->find();
        if($order['order_status'] == 1){
            Db::startTrans();
            try{
                //改订单状态
                $update = [
                    'order_status' => 2,
                    'order_back_transaction_id' => $back_order_id,
                    'order_paytime' => $today,
                ];
                Db::table('up_order')->where('order_no',$num)->update($update);
                Db::table('up_u_user')->where('user_id', $order['order_user_id'])->setInc('user_money',$order['order_coin']);
                //原先有多少，加进去
                Db::table('up_u_user')->where('user_id', $order['order_user_id'])->setInc('user_money_oldall',$order['order_coin']);
                Db::commit();
                //收入记录
                allInRevenue(1,$order['order_coin'],$order['order_user_id'],$order['order_id'],$order['order_user_pay']);
                //支付成功通知：
//                $title = '下单成功';
//                $content = '下单成功，友情提醒：快递发出15天内未收到货物，请及时联系我司客服，核实订单情况；快递发出超过20天未收到货物，也未与我司客服联系，我司将无法处理。';
//                allInNotice($title,$content,2,$order['user_id'],$order['order_id'],$order['order_contract']);
//                try{
//                    $this->Jpush(1, $order['user_id'], '下单成功', ['n_id' => $order['order_id'],'type' => $order['order_contract'],'n_type' => 2]);
//                }catch(\Exception $e){
//                }
                return true;
            }catch (\Exception $e) {
                Db::rollback();
                return false;
            }
        }else{
            return false;
        }
    }
    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
        if(is_string($alias) || is_int($alias)){
            $alias = (string)$alias;
        }
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        $push->message($message, [
//            'title' => 'Hello',
            'content_type' => 'text',
            'extras' => $extras
        ]);
        return $push->send();
    }

    //-------------------------------------------erp---------------------------------------------
    public function getHotsByData($list,$user_id)
    {
        foreach($list as $k => $v){
            $this->setGod($v['h_id'],$v['h_time']);
            $img = trim($v['h_image'], ',');
            if($v['h_cate'] == 1){
                if($img){
                    $list[$k]['h_image'] = explode(',', $img);
                }else{
                    $list[$k]['h_image'] = [];
                }
            }
            $list[$k]['like_u'] = 0;
            $like_u = Db::table('up_like')
                ->where('l_user_id', $user_id)
                ->where('l_other_user_id', $v['h_user_id'])
                ->find();
            if($like_u){
                $list[$k]['like_u'] = 1;
            }
            $list[$k]['god'] = [];
            $god_c = Db::table('up_comment')
                ->where('comment_hot_id', $v['h_id'])
                ->where('comment_god', 2)
                ->find();
            if($god_c){
                $list[$k]['god'] = $god_c;
                //我是赞是踩
                $list[$k]['god']['god_zan'] = 0;
                $zan_c = Db::table('up_zan')
                    ->where('zan_com_id', $god_c['comment_id'])
                    ->where('zan_com_type', 1)
                    ->where('zan_user_id', $user_id)
                    ->value('zan_type');
                if($zan_c){
                    $list[$k]['god']['god_zan'] = $zan_c;
                }
            }
            //
            $zan_h = Db::table('up_zan')
                ->where('zan_com_id', $v['h_id'])
                ->where('zan_com_type', 3)
                ->where('zan_user_id', $user_id)
                ->value('zan_type');
            $list[$k]['hot_zan'] = 0;
            if($zan_h){
                $list[$k]['hot_zan'] = $zan_h;
            }
        }
        return $list;
    }

    /**
     * 谁先到100赞，谁就是神怼
     * 12小时之内没有达到100赞且不得低于10赞的评论，谁最高谁是神怼，如果都没有超过10赞的评论，那这个动态就没有神怼，除非后台指定
     * @param $h_id
     * @param $h_time
     */
    public function setGod($h_id,$h_time)
    {
        $nowTime = time();
        $haveGod = Db::table('up_comment')
            ->where('comment_hot_id',$h_id)
            ->where('comment_god',2)
            ->find();
        if(!$haveGod){
            $hotTime = strtotime($h_time);
            if($nowTime - $hotTime >= 43200){
                $have = Db::table('up_comment')
                    ->where('comment_hot_id',$h_id)
                    ->where('comment_yes','>=',10)
                    ->order('comment_yes DESC')
                    ->page(1,1)
                    ->field('comment_id')
                    ->find();
            }else{
                $have = Db::table('up_comment')
                    ->where('comment_hot_id',$h_id)
                    ->where('comment_yes','>=',100)
                    ->order('comment_yes DESC')
                    ->page(1,1)
                    ->field('comment_id')
                    ->find();
            }
            if($have){
                Db::table('up_comment')
                    ->where('comment_id',$have['comment_id'])
                    ->setField('comment_god',2);
            }
        }
        //------------------
    }
    /**
     * 送豆
     */
    public function sendDou($from,$id)
    {
        if($from == 1){
            $field = 'comment_reply_user_id,comment_yes';
            $data = Db::table('up_comment')->where('comment_id', $id)->field($field)->find();
            $int = Db::table('up_comment')->where('comment_id', $id)->value('comment_dou_int');
            if($data['comment_yes'] >= 1000 && $int == 0){
                Db::table('up_u_user')->where('user_id', $data['comment_reply_user_id'])->setInc('user_money',5);
                Db::table('up_u_user')->where('user_id', $data['comment_reply_user_id'])->setInc('user_money_oldall',5);
                Db::table('up_comment')->where('comment_id', $id)->setInc('comment_dou_int');
                allInRevenue(3,5,$data['comment_reply_user_id'],$id);
            }
            $int = Db::table('up_comment')->where('comment_id', $id)->value('comment_dou_int');
            if($data['comment_yes'] >= 5000 && $int == 1){
                Db::table('up_u_user')->where('user_id', $data['comment_reply_user_id'])->setInc('user_money',25);
                Db::table('up_u_user')->where('user_id', $data['comment_reply_user_id'])->setInc('user_money_oldall',25);
                Db::table('up_comment')->where('comment_id', $id)->setInc('comment_dou_int');
                allInRevenue(3,25,$data['comment_reply_user_id'],$id);
            }
            $int = Db::table('up_comment')->where('comment_id', $id)->value('comment_dou_int');
            if($data['comment_yes'] > 5000 && $int == 2){
                Db::table('up_u_user')->where('user_id', $data['comment_reply_user_id'])->setInc('user_money',20);
                Db::table('up_u_user')->where('user_id', $data['comment_reply_user_id'])->setInc('user_money_oldall',20);
                Db::table('up_comment')->where('comment_id', $id)->setInc('comment_dou_int');
                allInRevenue(3,20,$data['comment_reply_user_id'],$id);
            }
        }elseif ($from == 2){
            $field = 'comtt_one_user_id,comtt_yes';
            $data = Db::table('up_comment_tt')->where('comtt_id', $id)->field($field)->find();
            $int = Db::table('up_comment_tt')->where('comtt_id', $id)->value('comtt_dou_int');
            if($data['comtt_yes'] >= 1000 && $int == 0){
                Db::table('up_u_user')->where('user_id', $data['comtt_one_user_id'])->setInc('user_money',5);
                Db::table('up_u_user')->where('user_id', $data['comtt_one_user_id'])->setInc('user_money_oldall',5);
                Db::table('up_comment_tt')->where('comtt_id', $id)->setInc('comtt_dou_int');
                allInRevenue(4,5,$data['comtt_one_user_id'],$id);
            }
            $int = Db::table('up_comment_tt')->where('comtt_id', $id)->value('comtt_dou_int');
            if($data['comtt_yes'] >= 5000 && $int == 1){
                Db::table('up_u_user')->where('user_id', $data['comtt_one_user_id'])->setInc('user_money',25);
                Db::table('up_u_user')->where('user_id', $data['comtt_one_user_id'])->setInc('user_money_oldall',25);
                Db::table('up_comment_tt')->where('comtt_id', $id)->setInc('comtt_dou_int');
                allInRevenue(4,25,$data['comtt_one_user_id'],$id);
            }
            $int = Db::table('up_comment_tt')->where('comtt_id', $id)->value('comtt_dou_int');
            if($data['comtt_yes'] > 5000 && $int == 2){
                Db::table('up_u_user')->where('user_id', $data['comtt_one_user_id'])->setInc('user_money',20);
                Db::table('up_u_user')->where('user_id', $data['comtt_one_user_id'])->setInc('user_money_oldall',20);
                Db::table('up_comment_tt')->where('comtt_id', $id)->setInc('comtt_dou_int');
                allInRevenue(4,20,$data['comtt_one_user_id'],$id);
            }
        }elseif ($from == 3){
            $field = 'h_user_id,h_yes';
            $data = Db::table('up_hot')->where('h_id', $id)->field($field)->find();
            $int = Db::table('up_hot')->where('h_id', $id)->value('h_dou_int');
            if($data['h_yes'] >= 1000 && $int == 0){
                Db::table('up_u_user')->where('user_id', $data['h_user_id'])->setInc('user_money',5);
                Db::table('up_u_user')->where('user_id', $data['h_user_id'])->setInc('user_money_oldall',5);
                Db::table('up_hot')->where('h_id', $id)->setInc('h_dou_int');
                allInRevenue(5,5,$data['h_user_id'],$id);
            }
            $int = Db::table('up_hot')->where('h_id', $id)->value('h_dou_int');
            if($data['h_yes'] >= 5000 && $int == 1){
                Db::table('up_u_user')->where('user_id', $data['h_user_id'])->setInc('user_money',25);
                Db::table('up_u_user')->where('user_id', $data['h_user_id'])->setInc('user_money_oldall',25);
                Db::table('up_hot')->where('h_id', $id)->setInc('h_dou_int');
                allInRevenue(5,25,$data['h_user_id'],$id);
            }
            $int = Db::table('up_hot')->where('h_id', $id)->value('h_dou_int');
            if($data['h_yes'] > 5000 && $int == 2){
                Db::table('up_u_user')->where('user_id', $data['h_user_id'])->setInc('user_money',20);
                Db::table('up_u_user')->where('user_id', $data['h_user_id'])->setInc('user_money_oldall',20);
                Db::table('up_hot')->where('h_id', $id)->setInc('h_dou_int');
                allInRevenue(5,20,$data['h_user_id'],$id);
            }
        }
    }
}